package top.chenfu.blog.controller;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.chenfu.blog.beans.ResponseData;
import top.chenfu.blog.entity.Article;
import top.chenfu.blog.entity.User;
import top.chenfu.blog.service.ArticleService;
import top.chenfu.blog.service.PvService;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Auther chenfu
 * @2019/10/30 18:05
 * @Desc
 */
@RestController
@RequestMapping("/article")
@Slf4j
public class ArticleController {

    private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyyMMdd");

    @Autowired
    private ArticleService articleService;

    @Autowired
    private PvService pvService;

    @Value("${image.root.path}")
    private String imageRootPath;

    @Value("${default.uId}")
    private Long defautUid;

    /**
     * 文章列表
     *
     * @param status
     * @param page
     * @param count
     * @param keywords 搜索的关键字
     * @return
     */
    @GetMapping("/all")
    public Map<String, Object> getArticlesByStatus(@RequestParam(value = "state", defaultValue = "1") Integer status, @RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "count", defaultValue = "6") Integer count, String keywords) {
//        匿名访问时，查看用户ID为默认值的用户博客，以后再改进
        long uid = defautUid;
        Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        log.info("obj={},classType={}", obj, obj.getClass());
//        没登陆时访问时，obj是匿名用户，可以打印obj来看
        if (obj instanceof User) {
            uid = ((User) obj).getId();
        }
        int totalCount = articleService.getArticleCountByState(status, uid, keywords);
        List<Article> articles = articleService.getArticleByState(status, uid, page, count, keywords);
        Map<String, Object> map = new HashMap<>();
        map.put("totalCount", totalCount);
        map.put("articles", articles);
        return map;
    }

    /**
     * 博客详情
     *
     * @param aid
     * @return
     */
    @GetMapping("/{aid}")
    public Article getArticleById(@PathVariable Long aid) {
        return articleService.getArticleById(aid);
    }

    @PostMapping
    public ResponseData addNewArticle(Article article) {
        if (articleService.addNewArticle(article) > 0) {
            return ResponseData.defaultSuccess("文章保存成功！");
        }
        return ResponseData.defaultFail(article.getState() == 0 ? "文章保存失败！" : "文章发表失败！");
    }

    /**
     * 博客文章删除，放入回收站
     *
     * @param aids  要删除的博客数组
     * @param state 博客当前的状态·根据用户当前的状态来判断是要进回收站还是直接删
     * @return ResponseData
     */
    @PutMapping("/dustbin")
    public ResponseData updateArticlesState(Long[] aids, Integer state) {
        List<Long> ids = Arrays.asList(aids);
        if (articleService.updateArticleState(ids, state) == aids.length) {
            return ResponseData.defaultSuccess("删除成功！");
        }
        return ResponseData.defaultFail("删除失败！");
    }

    /**
     * 还原博客
     *
     * @param articleId 博客ID
     * @return ResponseData
     */
    @PutMapping("/restore")
    public ResponseData restoreArticle(Long articleId) {
        if (articleService.restoreArticle(articleId) > 0) {
            return ResponseData.defaultSuccess("还原成功！");
        }
        return ResponseData.defaultFail("还原失败！");
    }

    @GetMapping("/dataStatistics")
    public Map<String, Object> dataStatistics() {
        Map<String, Object> map = new HashMap<>();
        List<String> categories = pvService.getCategories();
        List<Integer> dataStatistics = pvService.getPvStatistics();
        map.put("categories", categories);
        map.put("ds", dataStatistics);
        return map;
    }

    @PostMapping("/uploadimg")
    public ResponseData uploadImg(HttpServletRequest request, MultipartFile image) {
//        基本路径 formart==项目路径/image/20191101
        String filePath = File.separator + imageRootPath + File.separator + SDF.format(new Date());
        String httpFilePath = "/" + imageRootPath + "/" + SDF.format(new Date());
        log.info("filePath:{}", filePath);
//        获得真实路径
        String imgRealPath = request.getServletContext().getRealPath(filePath);
        log.info("imgRealPath:{}", imgRealPath);
        File imagePath = new File(imgRealPath);
        if (!imagePath.exists()) {
            imagePath.mkdirs();
        }
        String imageName = UUID.randomUUID().toString().replaceAll("-", "") + "_" + Objects.requireNonNull(image.getOriginalFilename()).replaceAll(" ", "");
        try {
            log.info("imagePath:{},imagePath:{}", imagePath, imageName);
            IOUtils.write(image.getBytes(), new FileOutputStream(new File(imagePath, imageName)));
            String url = new StringBuffer(request.getScheme())
                    .append("://").append(request.getServerName()).append(":")
                    .append(request.getServerPort())
                    .append(request.getContextPath())
                    .append(httpFilePath)
                    .append("/").append(imageName)
                    .toString();
            log.info("url:{}", url);
            return ResponseData.defaultSuccess(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseData.defaultFail("上传失败！");
    }

}
